from pms import db
from .models import Employee,Department
from flask import request, Blueprint,render_template,jsonify
from flask.views import MethodView
from  pms_app import emp
# emp = Blueprint('emp',__name__)


class EmployeeListView(MethodView):

    def get(self):
        key = request.args.get('key','')
        employees = db.session.query(Employee).filter(Employee.name.contains(key)).all()
        table_header = '''
        <table border="1">
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>地址</th>
        <th>工资</th>
    </tr>'''
        rows=''
        for emp in employees:
            rows += "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>".format(emp.id,emp.name,emp.address,emp.salary)
        return table_header+rows+'</table>'
        # return render_template('emp-list-ajax.html',employees=employees)

emp.add_url_rule('/list/',view_func=EmployeeListView.as_view('emp_list'))


@emp.route('/query_dept/')
def query_detp():
    depts = db.session.query(Department).all()
    return jsonify([detp.to_json() for detp in depts])

@emp.route('/query_emp/')
def query_emp():
    return render_template('pms_ajax_emp.html')

@emp.route('/ajax_query/')
def ajax_query():
    id = request.args.get('id', '')
    name = request.args.get('name', '')
    print(id+','+name)
    employees = db.session.query(Employee).filter(Employee.department_id == id).filter(Employee.name.contains(name)).all()
    return jsonify([emp.to_json() for emp in employees])
